package de.slothsoft.android4swing;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

final class AndroidResourceConverter {

    private static final String ELEMENT_LINE = "string";
    private static final String ATTRIBUTE_KEY = "name";

    public static Map<String, String> convertToMap(String xml) throws IOException {
	try {
	    Document document = createDocument(xml);

	    NodeList nodeList = document.getElementsByTagName(ELEMENT_LINE);
	    Map<String, String> result = new HashMap<>();
	    for (int i = 0; i < nodeList.getLength(); i++) {
		Node node = nodeList.item(i);
		if (node.getNodeType() == Node.ELEMENT_NODE) {
		    Element element = (Element) node;
		    String key = element.getAttribute(ATTRIBUTE_KEY);
		    String value = element.getChildNodes().item(0).getNodeValue();
		    result.put(key, value);
		}
	    }
	    return result;
	} catch (SAXException | ParserConfigurationException e) {
	    throw new IOException("Could not parse XML file", e);
	}
    }

    protected static Document createDocument(String xml) throws SAXException, IOException, ParserConfigurationException {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document document = builder.parse(new InputSource(new StringReader(xml)));
	document.getDocumentElement().normalize();
	return document;
    }

    private AndroidResourceConverter() {
	// hide util class
    }

}